package com.jhw.ymcc.security;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jhw.ymcc.domain.Login;
import com.jhw.ymcc.domain.Permission;
import com.jhw.ymcc.service.ILoginService;
import com.jhw.ymcc.service.IPermissionService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: Bug修复机
 * @date: 2022年10月23日 ： 10:33
 * @version: ver1.0
 * @email tangli@itsource.cn
 */
@Component // 把当前对象交给spring管理，跟@Bean一样的
public class LoginDetailService implements UserDetailsService {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private IPermissionService permissionService;

    /**
     * 根据账号查询用户，放入到UserDetails中
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.根据账号查询用户信息
        Login login = selectLoginByUserName(username);
        if (login != null){
            // 2.根据用户id查询用户权限信息
            List<Permission> permissions = permissionService.selectPermissionsByLoginId(login.getId());
            if (permissions != null){

                List<SimpleGrantedAuthority> collect = permissions.stream().map(p -> new SimpleGrantedAuthority(p.getSn())
                ).collect(Collectors.toList());


                return new User(login.getUsername(),
                        login.getPassword(),
                        login.getEnabled(),
                        login.getAccountNonExpired(),
                        login.getCredentialsNonExpired(),
                        login.getAccountNonLocked(),
                        collect);
            }

        }
        // 如果查询不到直接返回null
        return null;
    }

    private Login selectLoginByUserName(String username) {
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);
        return loginService.selectOne(wrapper);
    }
}